<?php

namespace app\common\model\platform;

use app\common\model\addon\Addons;
use app\common\model\BaseModel;
use app\common\model\user\UserPermission;
use hiduoke\services\CloudServer;

/**
 * Class PlatformAddon
 * @package app\common\model\platform
 * User: liuhongbin
 * Date: 2022-02-16 15:23
 */
class PlatformAddon extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 字段类型或者格式转换
     * @var array
     */
    protected $type = [
        'config' => 'json'
    ];


    /**
     * 模型名称
     * @var string
     */
    protected $name = 'platform_addon';

    public static function onAfterInsert($row)
    {
        $plaid = $row->plaid;
        $platform = (new Platform())->where(['plaid' => $plaid])->find();
        if ($platform['type'] == 2) {
            $Wxapp = new PlatformWxapp();
            $Wxapp->addon_name = $row->addon_name;
            $Wxapp->plaid = $plaid;
            $Wxapp->save();
            $platform->addon_name = $row->addon_name;
            $platform->save();
        }
    }

    /**
     * 获取平台应用配置
     * @param string $addon_name
     * @param int $plaid
     * @return array|mixed
     */
    public function getPlatformAddonConfig($addon_name = '', $plaid = 0)
    {
        $plaid = $plaid ?: get_plaid();
        $addon_name = $addon_name ?: get_addon();
        $res = $this->where(['plaid' => $plaid, 'addon_name' => $addon_name])->field('config')->findOrEmpty();
        return $res->config ?? [];
    }

    /**
     * 应用名称对应添加次数
     * @return array
     */
    public function getPlatformAddonCountList()
    {
        $res = $this->field(['COUNT(`addon_name`) as count', 'addon_name'])->group('addon_name')->select()->toArray();
        $counts = [];
        foreach ($res as $key => $value) {
            $counts[$value['addon_name']] = $value['count'];
        }
        return $counts;
    }

    /**
     * 获取已使用的应用数组
     * @return array
     */
    public function getUsefulAddons()
    {
        $CloudServer = (new CloudServer());
        $res = $CloudServer->getSiteAddonsCount([]);
        $local = $this->getPlatformAddonCountList();
        if ($res['code'] != 0) {
            $cloud = [];
        } else {
            $cloud = $res['data'];
        }
        $usefulAddons = [];
        foreach ($local as $key => $value) {
            if (!isset($cloud[$key])) {
                $usefulAddons[] = $key;
            } else if ($cloud[$key] > $value) {
                $usefulAddons[] = $key;
            }
        }
        return $usefulAddons;
    }

    /**
     * 获取客户端可用的应用标识
     * @return array ['dk_bk','dk_qk']
     */
    public function getCustomerUsefulAddonNames()
    {
        $names = (new Addons())->getAllAddonNames();
        $cloud_addon = (new CloudServer())->getSiteAddonTokenCount();
        $useful_names = [];
        foreach ($names as $key => $value) {
            if (isset($cloud_addon[$value])) {
                $count_msg = $cloud_addon[$value];
                if ($count_msg['surplus_count'] > 0) {
                    $useful_names[] = $value;
                }
            } else {
                $useful_names[] = $value;
            }
        }
        return $useful_names;
    }

//    public function addon()
//    {
//            return $this->hasOne(Addons::class, 'name', 'addon_name')->append(['default_url', 'auth', 'auth_key_title']);
//    }

    public function getPlatformAttr($val, $data)
    {
        return (new Platform())->where(['plaid' => $data['plaid']])->find();
    }

    public function getAddonAttr($value, $data)
    {
        $res = (new Addons())->where('name', $data['addon_name'])->append(['default_url'])->find();
        if ($res) {
            $res = $res->toArray();
            $res['default_url'] = str_replace('plaid=0', 'plaid=' . $data['plaid'], $res['default_url']);
            return $res;
        } else {
            return false;
        }
    }

    public function scopeCount($query)
    {
        $query->whereIn('addon_name', $this->getUsefulAddons());
    }

    public function searchAddonAttr($query, $value, $data)
    {
        $addon_names = [];
        $addons = (new Addons())->where('status', 1)->field('name')->select()->toArray();
        foreach ($addons as $key => $value) {
            $addon_names[] = $value['name'];
        }
        $query->where('addon_name', 'in', $addon_names);
    }

}
